/* Copyright 2009 CtrlSpace Platform
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * Contributor(s):
 * 	Marc Obaldo (marcklaser@gmail.com)
 */

dojo.provide("ctrlspace.ui.CreateJSFileDialog");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");

dojo.declare("ctrlspace.ui.CreateJSFileDialog", [dijit._Widget, dijit._Templated], {
	templateString : dojo.cache("ctrlspace.ui", "templates/CreateJSFileDialog.html"),
	widgetsInTemplate: true,
	
	// Post create
	postCreate : function() {
		this.inherited(arguments);
	},
	
	// Methods
	show: function() {
		this.dialog.show();
	},
	
	hide: function()
	{
		this.dialog.destroyRecursive();
	},
	
	destroy: function(preserveDom) {
		this.inherited(arguments);
	},
	
	createJSFile: function(jsFileName, jsFileLocation) {
		var call = dojo.xhrPost({
			url: ctrlspace.config.projectManagerUrl,
			content: {
				command: "create_js",
				fileName: jsFileName,
				fileLocation: jsFileLocation
			},
			handleAs: 'json',
			load: dojo.hitch(this, "createFileSuccess"),
			error: dojo.hitch(this, "createFileFailure")
		});
	},
	
	createFileSuccess: function(file) {
		// success, destroy dialog and update UI
		this.hide();
		this.destroy();
		IDE.UI.setStatus('JS File created successfully.', ctrlspace.config.STATUS_SUCCESS, 5);
		IDE.UI.projectCreated(file);
	},
	
	createFileFailure: function(error) {
	},
	
	// Template events
	_submit: function() {
		if (!this.jsFileName.isValid()) {
			this.jsFileName.displayMessage(this.jsFileName.getErrorMessage());
			return;
		}
		
		dojo.attr(this.submitButton, 'disabled', true);
		
		var jsFileName = this.jsFileName.value;
		var jsFileLocation = this.jsFileLocation.value;
		
		IDE.UI.setStatus('Creating JS File...', ctrlspace.config.STATUS_PROGRESS);

		this.createJSFile(jsFileName, jsFileLocation);
	}
});